package com.example.dance.service;

import com.example.dance.mapper.VideoMapper;
import com.example.dance.mapper.VideoPointsMapper;
import com.example.dance.pojo.Video;
import com.example.dance.pojo.VideoPoint;
import com.example.dance.util.RandomUtil;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class UploadService {
    private static final String CURRENT_DIR = System.getProperty("user.dir");

    @Autowired
    VideoMapper videoMapper;

    @Autowired
    VideoPointsMapper videoPointsMapper;

    @Transactional(rollbackFor = Exception.class)
    public void uploadService(MultipartFile videoFile,
                             String title,
                             String desc,
                             int type,
                             List<VideoPoint> points) throws IOException {
        try {
            String videoSrc = saveVideoFile(videoFile);
            //System.out.println(videoSrc);
            String imgSrc;
            imgSrc=saveMiddleFrame(CURRENT_DIR+"/upload/"+videoSrc);
            //System.out.println(imgSrc);
            int videoId = saveVideoInfo(videoSrc,title,imgSrc,desc,type);
            saveVideoPoint(videoId,points);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }

    }

    public String saveVideoFile(MultipartFile videoFile)  {

        if (videoFile.isEmpty()) {
            return null;
        }
        String fileName = RandomUtil.generateByRandom(10)+".mp4";

        File origin=new File(CURRENT_DIR+"/upload");
        if(!origin.exists()){
            origin.mkdirs();
        }

        File target=new File(origin+"/"+fileName);

        int count=0;
        while (target.exists()&&count<5){
            fileName=RandomUtil.generateByRandom(10+count)+".mp4";
            target=new File(origin+"/"+fileName);
            count++;
        }

        try {
            videoFile.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileName;

    }

    public String saveMiddleFrame(String videoPath) throws Exception {
        avutil.av_log_set_level(avutil.AV_LOG_QUIET);  // 完全静默
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
        grabber.start();

        int totalFrames = grabber.getLengthInFrames();  // 获取总帧数
        int middleFrame = totalFrames / 2;              // 计算中间帧位置
        int skipFrames = 5;                             // 跳过前5帧避免黑屏

        // 定位到中间帧附近（跳过无效帧）
        for (int i = 0; i < middleFrame + skipFrames && i < totalFrames; i++) {
            grabber.grabFrame();
        }

        // 获取中间帧并转换为BufferedImage
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage srcImage = converter.convert(grabber.grabImage());

        // 等比例缩放（例如缩放到宽度800px）
        int originalWidth = srcImage.getWidth();
        int originalHeight = srcImage.getHeight();
        int targetWidth = 800;
        int targetHeight = (int) ((double) targetWidth / originalWidth * originalHeight);

        // 创建缩放后的图像
        BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_3BYTE_BGR);
        scaledImage.getGraphics().drawImage(
                srcImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null
        );

        String fileName = RandomUtil.generateByRandom(10)+".jpg";

        File origin=new File(CURRENT_DIR+"/img");
        if(!origin.exists()){
            origin.mkdirs();
        }

        File target=new File(origin+"/"+fileName);

        int count=0;
        while (target.exists()&&count<5){
            fileName=RandomUtil.generateByRandom(10+count)+".jpg";
            target=new File(origin+"/"+fileName);
            count++;
        }
        // 保存到指定路径
        ImageIO.write(scaledImage, "jpg", target);

        grabber.stop();  // 释放资源
        return fileName;
    }

    public int saveVideoInfo(String videoSrc,String title,String imgSrc,String desc,int type) {
        Video video=new Video(videoSrc,title,imgSrc,desc,type);
        videoMapper.insertNewVideo(video);
        System.out.println("upload:"+video);
        return video.getVideoId();
    }

    public int saveVideoPoint(int videoId,List<VideoPoint> points) {
        for (VideoPoint point:
             points) {
            point.setVideoId(videoId);
            videoPointsMapper.insertNewPoint(point);
        }
        return 0;
    }
}
